package cn.ibizlab.modeling.addin.plm4modeling.plugin.groovy.sysutil;

import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.util.ObjectUtils
import org.springframework.util.StringUtils

import freemarker.template.utility.StringUtil
import groovy.transform.CompileStatic;
import java.util.regex.Matcher
import java.util.regex.Pattern
import net.ibizsys.central.cloud.core.security.EmployeeContext
import net.ibizsys.central.dataentity.IDataEntityRuntime
import net.ibizsys.central.dataentity.action.IDEActionPluginRuntime2;
import net.ibizsys.central.dataentity.service.DEMethodPluginRuntimeRepo;
import net.ibizsys.central.plugin.util.res.SysHtml2MDTranslatorRuntime
import net.ibizsys.central.plugin.util.res.SysHtml2TextTranslatorRuntime
import net.ibizsys.central.util.IEntityDTO;
import net.ibizsys.central.util.ISearchContextDTO
import net.ibizsys.central.util.Inflector
import net.ibizsys.model.PSModelEnums.AIBuildState
import net.ibizsys.model.dataentity.action.IPSDEAction;
import net.ibizsys.modeling.core.dataentity.dto.PSAppViewDTO
import net.ibizsys.modeling.core.dataentity.dto.PSDataEntityDTO
import net.ibizsys.modeling.core.dataentity.dto.PSDevSlnSysDTO
import net.ibizsys.modeling.core.dataentity.dto.PSModuleDTO
import net.ibizsys.modeling.core.dataentity.dto.PSSysAppDTO
import net.ibizsys.modeling.core.dataentity.dto.PSSysModelGroupDTO
import net.ibizsys.modeling.core.dataentity.dto.PSSysReqModuleDTO
import net.ibizsys.modeling.core.dataentity.dto.PSSysSFPubDTO
import net.ibizsys.modeling.core.dataentity.dto.PSSysServiceAPIDTO
import net.ibizsys.modeling.core.dataentity.service.IPSAppViewService
import net.ibizsys.modeling.core.dataentity.service.IPSDataEntityService
import net.ibizsys.modeling.core.dataentity.service.IPSDevSlnSysService
import net.ibizsys.modeling.core.dataentity.service.IPSModuleService
import net.ibizsys.modeling.core.dataentity.service.IPSSubSysServiceAPIService
import net.ibizsys.modeling.core.dataentity.service.IPSSysAppService
import net.ibizsys.modeling.core.dataentity.service.IPSSysModelGroupService
import net.ibizsys.modeling.core.dataentity.service.IPSSysReqModuleService
import net.ibizsys.modeling.core.dataentity.service.IPSSysSFPubService
import net.ibizsys.modeling.core.dataentity.service.IPSSysServiceAPIService
import net.ibizsys.modeling.core.util.PSModels
import net.ibizsys.runtime.dataentity.IDataEntityRuntimeContext;
import net.ibizsys.runtime.util.ActionSessionManager
import net.ibizsys.runtime.util.DataTypeUtils
import net.ibizsys.runtime.util.JsonUtils

@CompileStatic
class PLMSysUtilRuntime extends net.ibizsys.central.cloud.core.sysutil.SysUtilRuntimeBase {
	private static final org.apache.commons.logging.Log log = LogFactory.getLog(PLMSysUtilRuntime.class);
	
	public final static String DEMODEL_SPACE = "SPACE";
	
	public final static String DEMODEL_PAGE = "PAGE";
	
	public final static String DEMODEL_PRODUCT = "PRODUCT";
	
	public final static String DEMODEL_IDEA = "IDEA";
	
	public final static String DEMODEL_SECTION = "SECTION"; 
	
	public final static String DEMODEL_CATEGORY = "CATEGORY";
	
	public final static String DEMODEL_COMMENT = "COMMENT";
	
	public final static String DEACTON__SPACE__GET_DEVSYS_DEFAULT = "GET_DEVSYS_DEFAULT";
	
	public final static String DEACTON__SPACE__BUILD_DEVSYS_ALL = "BUILD_DEVSYS_ALL";
	
	public final static String DEACTON__PRODUCT__BUILD_DEVSYS_AIREQ = "BUILD_DEVSYS_AIREQ";
	
	public final static String SECTION_SCREENSHOT = "系统截图";
	
	public final static String PLMUSER_AIREQ = "AIREQ";
	
	public final static String PLMUSER_AIJSON = "AIJSON";
	
	private DEMethodPluginRuntimeRepo deMethodPluginRuntimeRepo = new DEMethodPluginRuntimeRepo();
	
	@Autowired
	private IPSDevSlnSysService iPSDevSlnSysService = null;
	
	@Autowired
	private IPSSysModelGroupService iPSSysModelGroupService = null;
	
	@Autowired
	private IPSModuleService iPSModuleService = null;
	
	@Autowired
	private IPSSysAppService iPSSysAppService = null;
	
	@Autowired
	private IPSSysSFPubService iPSSysSFPubService = null;
	
	@Autowired
	private IPSSysServiceAPIService iPSSysServiceAPIService = null;
	
	@Autowired
	private IPSSubSysServiceAPIService iPSSubSysServiceAPIService = null;
	
	@Autowired
	private IPSDataEntityService iPSDataEntityService = null;
	
	@Autowired
	private IPSAppViewService iPSAppViewService = null;
	
	
	@Autowired
	private IPSSysReqModuleService iPSSysReqModuleService = null;
	
	@Qualifier(DEMODEL_SPACE)
	private IDataEntityRuntime spaceDataEntityRuntime = null;
	
	@Qualifier(DEMODEL_PAGE)
	private IDataEntityRuntime pageDataEntityRuntime = null;
	
	@Qualifier(DEMODEL_PRODUCT)
	private IDataEntityRuntime productDataEntityRuntime = null;
	
	@Qualifier(DEMODEL_IDEA)
	private IDataEntityRuntime ideaDataEntityRuntime = null;
	
	@Qualifier(DEMODEL_SECTION)
	private IDataEntityRuntime sectionDataEntityRuntime = null;
	
	@Qualifier(DEMODEL_CATEGORY)
	private IDataEntityRuntime categoryDataEntityRuntime = null;
	
	@Qualifier(DEMODEL_COMMENT)
	private IDataEntityRuntime commentDataEntityRuntime = null;
	
	private final static Pattern Regex = Pattern.compile("@(\\{.*?\\})");
	
	@Override
	protected void onInit() throws Exception {
		this.deMethodPluginRuntimeRepo.init(this.getSystemRuntime(), true);
		super.onInit();
	}
	
	protected DEMethodPluginRuntimeRepo getDEMethodPluginRuntimeRepo() {
		return this.deMethodPluginRuntimeRepo;
	}
	
	
	@Override
	protected void onInstall() throws Exception {
		super.onInstall();
		
		this.onRegisterDEMethodPluginRuntimes();
	}
	
	protected void onRegisterDEMethodPluginRuntimes() throws Exception{
		this.getDEMethodPluginRuntimeRepo().registerDEActionPluginRuntime(DEMODEL_SPACE, DEACTON__SPACE__GET_DEVSYS_DEFAULT, new IDEActionPluginRuntime2() {
			@Override
			public Object execute(IDataEntityRuntimeContext iDataEntityRuntimeContext, IPSDEAction iPSDEAction,	Object[] args, Object actionData) throws Throwable {
				return doGetDevSysDefault();
			}
		});
	
		this.getDEMethodPluginRuntimeRepo().registerDEActionPluginRuntime(DEMODEL_SPACE, DEACTON__SPACE__BUILD_DEVSYS_ALL, new IDEActionPluginRuntime2() {
			@Override
			public Object execute(IDataEntityRuntimeContext iDataEntityRuntimeContext, IPSDEAction iPSDEAction,	Object[] args, Object actionData) throws Throwable {
				doBuildDevSysAll();
				return null;
			}
		});
	
		this.getDEMethodPluginRuntimeRepo().registerDEActionPluginRuntime(DEMODEL_PRODUCT, DEACTON__PRODUCT__BUILD_DEVSYS_AIREQ, new IDEActionPluginRuntime2() {
			@Override
			public Object execute(IDataEntityRuntimeContext iDataEntityRuntimeContext, IPSDEAction iPSDEAction,	Object[] args, Object actionData) throws Throwable {
				doBuildDevSysAIReq()
				return null;
			}
		});
	}
	
	protected Object doGetDevSysDefault() throws Throwable{
		
		String strPSDevSlnSysId = ActionSessionManager.getAppContextMust().get(PSModels.PSDEVSLNSYS);
		
		ISearchContextDTO iSearchContextDTO = spaceDataEntityRuntime.createSearchContext();
		iSearchContextDTO.count(false).limit(10);
		
		iSearchContextDTO.eq("user_tag", "PSDEVSLNSYS");
		iSearchContextDTO.eq("user_tag2", strPSDevSlnSysId);
		
		List<IEntityDTO> list =	spaceDataEntityRuntime.selectDataSet("DEFAULT", iSearchContextDTO);
		if(!ObjectUtils.isEmpty(list)) {
			return list.get(0);
		}
		
		PSDevSlnSysDTO psDevSlnSysDTO = iPSDevSlnSysService.get(strPSDevSlnSysId);
		
		IEntityDTO spaceEntityDTO = spaceDataEntityRuntime.createEntity();
		
		String strLogicName = psDevSlnSysDTO.getLogicName();
		if(ObjectUtils.isEmpty(strLogicName)) {
			strLogicName = psDevSlnSysDTO.getName();
		}
		
		Random random = new Random();
		spaceEntityDTO.set("name", String.format("%s[Modeling系统]", strLogicName));
		String strId = String.format("M%s", random.nextInt(99999999));

		spaceEntityDTO.set("identifier", strId);
		spaceEntityDTO.set("visibility", "public");
		spaceEntityDTO.set("scope_type", "organization");
		spaceEntityDTO.set("scope_id", EmployeeContext.getCurrentMust().getOrgid());
		spaceEntityDTO.set("user_tag", "PSDEVSLNSYS");
		spaceEntityDTO.set("user_tag2", strPSDevSlnSysId);
		spaceEntityDTO.set("description", psDevSlnSysDTO.getMemo());
		
		spaceDataEntityRuntime.create(spaceEntityDTO);
		
		return spaceEntityDTO;
		
//		{
//			"members": [
//			  {
//				"name": "机构管理员",
//				"role_id": "admin",
//				"user_id": "3b0054d77baed2782d59410eab30d4f6",
//				"space_id": "7cc559dd-301b-0a4e-1c7d-ea42b0174fce",
//				"id": "7cc559dd-301b-0a4e-1c7d-ea42b0174fce||3b0054d77baed2782d59410eab30d4f6"
//			  }
//			],
//			"identifier": "MODELING01",
//			"visibility": "public",
//			"scope_type": "organization",
//			"scope_id": "4574e071f4379e0353c7d4ff5045350e",
//			"id": "7cc559dd-301b-0a4e-1c7d-ea42b0174fce",
//			"name": "modeling01"
//		  }
//		
		
		return null;
	}
	
	protected void doBuildDevSysAll() throws Throwable{
		
		IEntityDTO devSysSpace = (IEntityDTO)this.doGetDevSysDefault();
		
		String strLastSpaceId = ActionSessionManager.getAppContextIf().get(DEMODEL_SPACE);
		String strSpaceId = devSysSpace.getId();
		ActionSessionManager.getAppContextIf().set(DEMODEL_SPACE, strSpaceId);
		
		//查出页面
		Map<String, IEntityDTO> pageMap = new HashMap();
		if(true) {
			ISearchContextDTO iSearchContextDTO = pageDataEntityRuntime.createSearchContext();
			iSearchContextDTO.all().count(false);
			iSearchContextDTO.eq("space_id", devSysSpace.getId());
			iSearchContextDTO.eq("is_deleted", 0)
			
			List<IEntityDTO> list = pageDataEntityRuntime.selectDataSet("DEFAULT", iSearchContextDTO);
			if(!ObjectUtils.isEmpty(list)) {
				for(IEntityDTO item : list ) {
					String strUserTag = item.getString("user_tag", null);
					String strUserTag2 = item.getString("user_tag2", null);
					
					if(ObjectUtils.isEmpty(strUserTag)) {
						continue;
					}
					
					String strTag = ObjectUtils.isEmpty(strUserTag2)? strUserTag: String.format("%s:%s", strUserTag, strUserTag2.toLowerCase());
					pageMap.put(strTag, item);
				}
			}
		}
 		
		Map<String, PSSysModelGroupDTO> psSysModelGroupMap = new LinkedHashMap();
		Map<String, PSModuleDTO> psModuleMap = new LinkedHashMap();
		Map<String, PSSysAppDTO> psSysAppMap = new LinkedHashMap();
		Map<String, PSSysSFPubDTO> psSysSFPubMap = new LinkedHashMap();
		Map<String, PSSysServiceAPIDTO> psSysServiceAPIMap = new LinkedHashMap();
		
		Map<String, PSDataEntityDTO> psDataEntityMap = new LinkedHashMap();
		Map<String, PSAppViewDTO> psAppViewMap = new LinkedHashMap();
		
		if(true) {
			ISearchContextDTO iSearchContextDTO = iPSSysModelGroupService.createSearchContextDTO();
			iSearchContextDTO.all().count(false);
			List<PSSysModelGroupDTO> list = (List<PSSysModelGroupDTO>)iPSSysModelGroupService.getDataEntityRuntime().rawSelect(iPSSysModelGroupService.getDataEntityRuntime().getDefaultPSDEDataQuery(), iSearchContextDTO);
			if(!ObjectUtils.isEmpty(list)) {
				for(PSSysModelGroupDTO item : list ) {
					psSysModelGroupMap.put(item.getPSSysModelGroupId(), item);
				}
			}	
		}
		
		if(true) {
			ISearchContextDTO iSearchContextDTO = iPSModuleService.createSearchContextDTO();
			iSearchContextDTO.all().count(false);
			List<PSModuleDTO> list = (List<PSModuleDTO>)iPSModuleService.getDataEntityRuntime().rawSelect(iPSModuleService.getDataEntityRuntime().getDefaultPSDEDataQuery(), iSearchContextDTO);
			if(!ObjectUtils.isEmpty(list)) {
				for(PSModuleDTO item : list ) {
					psModuleMap.put(item.getPSModuleId(), item);
				}
			}
		}
		
		if(true) {
			ISearchContextDTO iSearchContextDTO = iPSSysAppService.createSearchContextDTO();
			iSearchContextDTO.all().count(false);
			List<PSSysAppDTO> list = (List<PSSysAppDTO>)iPSSysAppService.getDataEntityRuntime().rawSelect(iPSSysAppService.getDataEntityRuntime().getDefaultPSDEDataQuery(), iSearchContextDTO);
			if(!ObjectUtils.isEmpty(list)) {
				for(PSSysAppDTO item : list ) {
					psSysAppMap.put(item.getPSSysAppId(), item);
				}
			}
		}
		
		if(true) {
			ISearchContextDTO iSearchContextDTO = iPSSysSFPubService.createSearchContextDTO();
			iSearchContextDTO.all().count(false);
			List<PSSysSFPubDTO> list = (List<PSSysSFPubDTO>)iPSSysSFPubService.getDataEntityRuntime().rawSelect(iPSSysSFPubService.getDataEntityRuntime().getDefaultPSDEDataQuery(), iSearchContextDTO);
			if(!ObjectUtils.isEmpty(list)) {
				for(PSSysSFPubDTO item : list ) {
					psSysSFPubMap.put(item.getPSSysSFPubId(), item);
				}
			}
		}
		
		if(true) {
			ISearchContextDTO iSearchContextDTO = iPSSysServiceAPIService.createSearchContextDTO();
			iSearchContextDTO.all().count(false);
			List<PSSysServiceAPIDTO> list = (List<PSSysServiceAPIDTO>)iPSSysServiceAPIService.getDataEntityRuntime().rawSelect(iPSSysServiceAPIService.getDataEntityRuntime().getDefaultPSDEDataQuery(), iSearchContextDTO);
			if(!ObjectUtils.isEmpty(list)) {
				for(PSSysServiceAPIDTO item : list ) {
					psSysServiceAPIMap.put(item.getPSSysServiceAPIId(), item);
				}
			}
		}
		
		if(true) {
			ISearchContextDTO iSearchContextDTO = iPSDataEntityService.createSearchContextDTO();
			iSearchContextDTO.all().count(false);
			List<PSDataEntityDTO> list = (List<PSDataEntityDTO>)iPSDataEntityService.getDataEntityRuntime().rawSelect(iPSDataEntityService.getDataEntityRuntime().getDefaultPSDEDataQuery(), iSearchContextDTO);
			if(!ObjectUtils.isEmpty(list)) {
				for(PSDataEntityDTO item : list ) {
					psDataEntityMap.put(item.getPSDataEntityId(), item);
				}
			}
		}
		
		if(true) {
			ISearchContextDTO iSearchContextDTO = iPSAppViewService.createSearchContextDTO();
			iSearchContextDTO.all().count(false);
			List<PSAppViewDTO> list = (List<PSAppViewDTO>)iPSAppViewService.getDataEntityRuntime().rawSelect(iPSAppViewService.getDataEntityRuntime().getDefaultPSDEDataQuery(), iSearchContextDTO);
			if(!ObjectUtils.isEmpty(list)) {
				for(PSAppViewDTO item : list ) {
					psAppViewMap.put(item.getPSAppViewId(), item);
				}
			}
		}
		/*
		 * {
  "name": "测试",
  "is_published": 1,
  "FORMAT_TYPE": "HTML",
  "type": 2
}

{
  "title": "tst22",
  "type": "1",
  "format_type": "HTML",
  "space_id": "89d271d324209e0f59cfea1077b345b8",
  "parent_id": "8d34af2c4b452cf4dbd00498f8cf96b0",
  "attachments": [],
  "attentions": [
    {
      "user_id": "3b0054d77baed2782d59410eab30d4f6",
      "name": "机构管理员",
      "type": "40"
    }
  ],
  "is_shared": "0",
  "sequence": 1,
  "is_leaf": 1,
  "space_identifier": "M91581134",
  "is_archived": 0,
  "is_deleted": 0,
  "is_published": 0,
  "published": 0,
  "is_lock": 0,
  "is_shared_subset": "0",
  "space_name": "DemoSys[Modeling系统]",
  "space": "89d271d324209e0f59cfea1077b345b8",
  "name": "tst22"
}

		 */
		
		
		
		//初始化模型组
		if(true) {
			String strTag = String.format("%s", Inflector.getInstance().pluralize(PSModels.PSSYSMODELGROUP)).toUpperCase();
			IEntityDTO psSysModelGroupsPage= pageMap.get(strTag);
			if(psSysModelGroupsPage == null) {
				psSysModelGroupsPage = pageDataEntityRuntime.createEntity();
				psSysModelGroupsPage.set("space_id", strSpaceId);
				psSysModelGroupsPage.set("is_published", 1);
				psSysModelGroupsPage.set("type", 2);
				psSysModelGroupsPage.set("name", "模型组");
				psSysModelGroupsPage.set("user_tag", strTag);
				pageDataEntityRuntime.create(psSysModelGroupsPage);
				pageMap.put(strTag, psSysModelGroupsPage);
			}
			
			for(PSSysModelGroupDTO psSysModelGroupDTO : psSysModelGroupMap.values()) {
				if(ObjectUtils.isEmpty(psSysModelGroupDTO.getCodeName())) {
					continue;
				}
				
				strTag = String.format("%s:%s", PSModels.PSSYSMODELGROUP, psSysModelGroupDTO.getCodeName().toLowerCase());
				if(pageMap.containsKey(strTag)) {
					continue;
				}
				
				IEntityDTO psSysModelGroupPage = pageDataEntityRuntime.createEntity();
				this.fillPageDTO(psSysModelGroupPage, 1);
				psSysModelGroupPage.set("space_id", strSpaceId);
				psSysModelGroupPage.set("parent_id", psSysModelGroupsPage.getId());
				
				psSysModelGroupPage.set("name", psSysModelGroupDTO.getName());
				psSysModelGroupPage.set("title", psSysModelGroupDTO.getName());
				
				
				psSysModelGroupPage.set("user_tag", PSModels.PSSYSMODELGROUP);
				psSysModelGroupPage.set("user_tag2", psSysModelGroupDTO.getCodeName().toLowerCase());
				pageDataEntityRuntime.executeAction("PUBLISH_PAGE", null, [psSysModelGroupPage] as Object[]);
				
				pageMap.put(strTag, psSysModelGroupPage);
			}
		}
		
		if(true) {
			
			String strTag = String.format("%s", Inflector.getInstance().pluralize(PSModels.PSMODULE)).toUpperCase();
			IEntityDTO psModulesPage= pageMap.get(strTag);
			if(psModulesPage == null) {
				psModulesPage = pageDataEntityRuntime.createEntity();
				psModulesPage.set("space_id", strSpaceId);
				psModulesPage.set("is_published", 1);
				psModulesPage.set("type", 2);
				psModulesPage.set("name", "模块");
				psModulesPage.set("user_tag", strTag);
				pageDataEntityRuntime.create(psModulesPage);
				pageMap.put(strTag, psModulesPage);
			}
			
			for(PSModuleDTO psModuleDTO : psModuleMap.values()) {
				if(ObjectUtils.isEmpty(psModuleDTO.getCodeName())) {
					continue;
				}
				
				String strPSModelTag = psModuleDTO.getCodeName().toLowerCase();
				IEntityDTO folderPage = psModulesPage;
				if(!ObjectUtils.isEmpty(psModuleDTO.getPSSysModelGroupId())) {
					PSSysModelGroupDTO psSysModelGroupDTO = psSysModelGroupMap.get(psModuleDTO.getPSSysModelGroupId());
					if(psSysModelGroupDTO == null) {
						throw new Exception(String.format("无法获取指定模型组[%s]", psModuleDTO.getPSSysModelGroupId()));
					}
					
					if(StringUtils.hasLength(psSysModelGroupDTO.getCodeName())) {
						strPSModelTag = String.format("%s.%s", psSysModelGroupDTO.getCodeName(), strPSModelTag).toLowerCase();
						String strFolderTag = String.format("%s:%s:%s", Inflector.getInstance().pluralize(PSModels.PSMODULE).toUpperCase(), PSModels.PSSYSMODELGROUP, psSysModelGroupDTO.getCodeName().toLowerCase());
						folderPage = pageMap.get(strFolderTag);
						if(folderPage == null) {
							folderPage = pageDataEntityRuntime.createEntity();
							folderPage.set("space_id", strSpaceId);
							folderPage.set("parent_id", psModulesPage.getId());
							folderPage.set("is_published", 1);
							folderPage.set("type", 2);
							folderPage.set("name", psSysModelGroupDTO.getName());
							folderPage.set("user_tag", Inflector.getInstance().pluralize(PSModels.PSMODULE).toUpperCase());
							folderPage.set("user_tag2", String.format("%s:%s", PSModels.PSSYSMODELGROUP, psSysModelGroupDTO.getCodeName().toLowerCase()));
							pageDataEntityRuntime.create(folderPage);
							pageMap.put(strTag, folderPage);
						}
					}
				}
				
				strTag = String.format("%s:%s", PSModels.PSMODULE, strPSModelTag);
				IEntityDTO psModulePage = pageMap.get(strTag);
				if(psModulePage == null) {
					psModulePage = pageDataEntityRuntime.createEntity();
					this.fillPageDTO(psModulePage, 1);
					psModulePage.set("space_id", strSpaceId);
					psModulePage.set("parent_id", folderPage.getId());
					
					psModulePage.set("name", psModuleDTO.getName());
					psModulePage.set("title", psModuleDTO.getName());
					if(StringUtils.hasLength(psModuleDTO.getMemo())) {
						psModulePage.set("content", psModuleDTO.getMemo());
					}
					
					psModulePage.set("user_tag", PSModels.PSMODULE);
					psModulePage.set("user_tag2", strPSModelTag);
					pageDataEntityRuntime.executeAction("PUBLISH_PAGE", null, [psModulePage] as Object[]);
					
					pageMap.put(strTag, psModulePage);
				}
			}
		}
		
		if(true) {
			
			String strTag = String.format("%s", Inflector.getInstance().pluralize(PSModels.PSDATAENTITY)).toUpperCase();
			IEntityDTO psDataEntitiesPage= pageMap.get(strTag);
			if(psDataEntitiesPage == null) {
				psDataEntitiesPage = pageDataEntityRuntime.createEntity();
				psDataEntitiesPage.set("space_id", strSpaceId);
				psDataEntitiesPage.set("is_published", 1);
				psDataEntitiesPage.set("type", 2);
				psDataEntitiesPage.set("name", "实体");
				psDataEntitiesPage.set("user_tag", strTag);
				pageDataEntityRuntime.create(psDataEntitiesPage);
				pageMap.put(strTag, psDataEntitiesPage);
			}
			
			for(PSDataEntityDTO psDataEntityDTO : psDataEntityMap.values()) {
				if(ObjectUtils.isEmpty(psDataEntityDTO.getName())) {
					continue;
				}
				
				IEntityDTO folderPage = psDataEntitiesPage;
				if(ObjectUtils.isEmpty(psDataEntityDTO.getPSModuleId())) {
					continue;
				}
				
				PSModuleDTO psModuleDTO = psModuleMap.get(psDataEntityDTO.getPSModuleId());
				if(psModuleDTO == null) {
					throw new Exception(String.format("无法获取指定模块[%s]", psDataEntityDTO.getPSModuleId()));
				}
				if(!StringUtils.hasLength(psModuleDTO.getCodeName())) {
					continue;
				}
				
				String strPSModuleTag = psModuleDTO.getCodeName().toLowerCase();
				if(!ObjectUtils.isEmpty(psModuleDTO.getPSSysModelGroupId())) {
					PSSysModelGroupDTO psSysModelGroupDTO = psSysModelGroupMap.get(psModuleDTO.getPSSysModelGroupId());
					if(psSysModelGroupDTO == null) {
						throw new Exception(String.format("无法获取指定模型组[%s]", psModuleDTO.getPSSysModelGroupId()));
					}
					
					if(!StringUtils.hasLength(psSysModelGroupDTO.getCodeName())) {
						continue;
					}
					
					strPSModuleTag = String.format("%s.%s", psSysModelGroupDTO.getCodeName(), strPSModuleTag).toLowerCase();
					String strFolderTag = String.format("%s:%s:%s", Inflector.getInstance().pluralize(PSModels.PSDATAENTITY).toUpperCase(), PSModels.PSSYSMODELGROUP, psSysModelGroupDTO.getCodeName().toLowerCase());
					IEntityDTO subFolderPage = pageMap.get(strFolderTag);
					if(subFolderPage == null) {
						subFolderPage = pageDataEntityRuntime.createEntity();
						subFolderPage.set("space_id", strSpaceId);
						subFolderPage.set("parent_id", folderPage.getId());
						subFolderPage.set("is_published", 1);
						subFolderPage.set("type", 2);
						subFolderPage.set("name", psSysModelGroupDTO.getName());
						subFolderPage.set("user_tag", Inflector.getInstance().pluralize(PSModels.PSDATAENTITY).toUpperCase());
						subFolderPage.set("user_tag2", String.format("%s:%s", PSModels.PSSYSMODELGROUP, psSysModelGroupDTO.getCodeName().toLowerCase()));
						pageDataEntityRuntime.create(subFolderPage);
						pageMap.put(strFolderTag, subFolderPage);
					}
					folderPage = subFolderPage;
				}
				
				String strFolderTag = String.format("%s:%s:%s", Inflector.getInstance().pluralize(PSModels.PSDATAENTITY).toUpperCase(), PSModels.PSMODULE, strPSModuleTag);
				IEntityDTO subFolderPage = pageMap.get(strFolderTag);
				if(subFolderPage == null) {
					subFolderPage = pageDataEntityRuntime.createEntity();
					subFolderPage.set("space_id", strSpaceId);
					subFolderPage.set("parent_id", folderPage.getId());
					subFolderPage.set("is_published", 1);
					subFolderPage.set("type", 2);
					subFolderPage.set("name", psModuleDTO.getName());
					subFolderPage.set("user_tag", Inflector.getInstance().pluralize(PSModels.PSDATAENTITY).toUpperCase());
					subFolderPage.set("user_tag2", String.format("%s:%s", PSModels.PSMODULE, strPSModuleTag));
					pageDataEntityRuntime.create(subFolderPage);
					pageMap.put(strFolderTag, subFolderPage);
				}
				folderPage = subFolderPage;
				
				
				String strPSDataEntityTag = String.format("%s.%s", strPSModuleTag, psDataEntityDTO.getName()).toLowerCase();
				
				strTag = String.format("%s:%s", PSModels.PSDATAENTITY, strPSDataEntityTag);
				IEntityDTO psDataEntityPage = pageMap.get(strTag);
				if(psDataEntityPage == null) {
					psDataEntityPage = pageDataEntityRuntime.createEntity();
					this.fillPageDTO(psDataEntityPage, 1);
					psDataEntityPage.set("space_id", strSpaceId);
					psDataEntityPage.set("parent_id", folderPage.getId());
					
					psDataEntityPage.set("name", psDataEntityDTO.getName());
					psDataEntityPage.set("title", psDataEntityDTO.getLogicName());
					if(StringUtils.hasLength(psDataEntityDTO.getMemo())) {
						psDataEntityPage.set("content", psDataEntityDTO.getMemo());
					}
					
					psDataEntityPage.set("user_tag", PSModels.PSDATAENTITY);
					psDataEntityPage.set("user_tag2", strPSDataEntityTag);
					pageDataEntityRuntime.executeAction("PUBLISH_PAGE", null, [psDataEntityPage] as Object[]);
					
					pageMap.put(strTag, psDataEntityPage);
				}
			}
		}
		
		
		ActionSessionManager.getAppContextIf().set(DEMODEL_SPACE, strLastSpaceId);

		
//		{
//			"members": [
//			  {
//				"name": "机构管理员",
//				"role_id": "admin",
//				"user_id": "3b0054d77baed2782d59410eab30d4f6",
//				"space_id": "7cc559dd-301b-0a4e-1c7d-ea42b0174fce",
//				"id": "7cc559dd-301b-0a4e-1c7d-ea42b0174fce||3b0054d77baed2782d59410eab30d4f6"
//			  }
//			],
//			"identifier": "MODELING01",
//			"visibility": "public",
//			"scope_type": "organization",
//			"scope_id": "4574e071f4379e0353c7d4ff5045350e",
//			"id": "7cc559dd-301b-0a4e-1c7d-ea42b0174fce",
//			"name": "modeling01"
//		  }
//
		
		return null;
	}
	
	protected void doBuildDevSysAIReq() throws Throwable{
		
		
		//查询当前跟需求
		ISearchContextDTO iSearchContextDTO = iPSSysReqModuleService.createSearchContextDTO();
		iSearchContextDTO.all().count(false)
			.nvl(PSSysReqModuleDTO.FIELD_PPSSYSREQMODULEID)
			.nn(PSSysReqModuleDTO.FIELD_MODULETAG);
		
		List<PSSysReqModuleDTO> psSysReqModuleList = iPSSysReqModuleService.rawSelect(iSearchContextDTO);
		if(ObjectUtils.isEmpty(psSysReqModuleList)) {
//			log.debug("没有找到根需求模块");
//			return;
			throw new Exception("没有找到根需求模块");
		}
		
		for(PSSysReqModuleDTO psSysReqModule : psSysReqModuleList) {
			if(ObjectUtils.isEmpty(psSysReqModule.getModuleTag())) {
				continue;
			}
			
			if(psSysReqModule.getModuleTag().indexOf("PLM__") ==  0) {
				String strProductSN = psSysReqModule.getModuleTag().substring(5);
				doBuildDevSysAIReq(psSysReqModule, strProductSN);
			}
		}
		
		
		return null;
	}
	
	protected void doBuildDevSysAIReq(PSSysReqModuleDTO psSysReqModule, String productSN) throws Throwable{
		ISearchContextDTO iSearchContextDTO = productDataEntityRuntime.createSearchContext();
		iSearchContextDTO.eq("IDENTIFIER", productSN);
		List<IEntityDTO> list =productDataEntityRuntime.selectDataSet("MAIN", iSearchContextDTO);
		
		if(ObjectUtils.isEmpty(list)) {
			//log.warn("PLM未定义标识为[$productSN]的产品");
			//return;
			throw new Exception("PLM未定义标识为[$productSN]的产品");
		}
		
		//获取截图模块
		Map<String, PSSysReqModuleDTO> uiModulePSSysReqModuleMap = new LinkedHashMap();
		PSSysReqModuleDTO screenshotPSSysReqModule = new PSSysReqModuleDTO();
		screenshotPSSysReqModule.setPPSSysReqModuleId(psSysReqModule.getPSSysReqModuleId());
		//screenshotPSSysReqModule.setModuleTag("SCREENSHOT");
		screenshotPSSysReqModule.setModuleTag2("PDD_UIS");
		if(!this.iPSSysReqModuleService.rawSelect(screenshotPSSysReqModule, true)) {
			screenshotPSSysReqModule.setPSSysReqModuleName("界面原型");
			screenshotPSSysReqModule.setOrderValue(100);
			this.iPSSysReqModuleService.create(screenshotPSSysReqModule);
		}
		else {
			//查出全部子模块
			ISearchContextDTO psSysReqModuleSearchContextDTO =  this.iPSSysReqModuleService.createSearchContextDTO();
			psSysReqModuleSearchContextDTO.all().count(false);
			psSysReqModuleSearchContextDTO.eq(PSSysReqModuleDTO.FIELD_PPSSYSREQMODULEID, screenshotPSSysReqModule.getPSSysReqModuleId());
			psSysReqModuleSearchContextDTO.eq(PSSysReqModuleDTO.FIELD_MODULETAG2, "PDD_UIMODULE")
			List<PSSysReqModuleDTO> psSysReqModuleDTOList = this.iPSSysReqModuleService.rawSelect(psSysReqModuleSearchContextDTO);
			if(!ObjectUtils.isEmpty(psSysReqModuleDTOList)) {
				for(PSSysReqModuleDTO item : psSysReqModuleDTOList) {
					if(!StringUtils.hasLength(item.getPSSysReqModuleName())) {
						continue;
					}
					uiModulePSSysReqModuleMap.put(item.getPSSysReqModuleName(), item);
				}
			}
		}

		//实体原型
		Map<String, PSSysReqModuleDTO> modulePSSysReqModuleMap = new LinkedHashMap();
		
		PSSysReqModuleDTO modulesPSSysReqModule = new PSSysReqModuleDTO();
		modulesPSSysReqModule.setPPSSysReqModuleId(psSysReqModule.getPSSysReqModuleId());
		modulesPSSysReqModule.setModuleTag2("MDD_MODULES");
		if(!this.iPSSysReqModuleService.rawSelect(modulesPSSysReqModule, true)) {
			modulesPSSysReqModule.setPSSysReqModuleName("系统模块");
			modulesPSSysReqModule.setOrderValue(200);
			this.iPSSysReqModuleService.create(modulesPSSysReqModule);
		}
		else {
			//查出全部子模块
			ISearchContextDTO psSysReqModuleSearchContextDTO =  this.iPSSysReqModuleService.createSearchContextDTO();
			psSysReqModuleSearchContextDTO.all().count(false);
			psSysReqModuleSearchContextDTO.eq(PSSysReqModuleDTO.FIELD_PPSSYSREQMODULEID, modulesPSSysReqModule.getPSSysReqModuleId());
			psSysReqModuleSearchContextDTO.eq(PSSysReqModuleDTO.FIELD_MODULETAG2, "MDD_MODULE")
			List<PSSysReqModuleDTO> psSysReqModuleDTOList = this.iPSSysReqModuleService.rawSelect(psSysReqModuleSearchContextDTO);
			if(!ObjectUtils.isEmpty(psSysReqModuleDTOList)) {
				for(PSSysReqModuleDTO item : psSysReqModuleDTOList) {
					if(!StringUtils.hasLength(item.getPSSysReqModuleName())) {
						continue;
					}
					modulePSSysReqModuleMap.put(item.getPSSysReqModuleName(), item);
				}
			}
		}
		
		IEntityDTO product = list.get(0);
		
		String strName = product.getName();
		String strLastProductId = ActionSessionManager.getAppContextIf().get(DEMODEL_PRODUCT);
		String strProductId = product.getId();
		ActionSessionManager.getAppContextIf().set(DEMODEL_PRODUCT, strProductId);
		//查询全部需求
		if(true) {
			
			ISearchContextDTO sectionSearchContextDTO = sectionDataEntityRuntime.createSearchContext();
			sectionSearchContextDTO.all().count(false);
			sectionSearchContextDTO.eq("owner_type", "product");
			sectionSearchContextDTO.eq("owner_subtype", "idea");
			sectionSearchContextDTO.eq("owner_id", strProductId);
			IEntityDTO section = null;
			List<IEntityDTO> sectionList = sectionDataEntityRuntime.selectDataSet("DEFAULT", sectionSearchContextDTO);
			if(!ObjectUtils.isEmpty(sectionList)) {
				for(IEntityDTO item : sectionList ) {
					//逐个演进
					if(SECTION_SCREENSHOT.equals(item.getName())) {
						section = item;
						break;
					}
				}
			}
			
			if(section == null) {
				throw new Exception("产品[$productSN]未定义分区");
			}
			
			Map<String, PSSysReqModuleDTO> uiPSSysReqModuleMap = new LinkedHashMap();
			
			//查出根分类
			ISearchContextDTO categorySearchContextDTO = categoryDataEntityRuntime.createSearchContext();
			categorySearchContextDTO.all().count(false);
			categorySearchContextDTO.eq("owner_type", "product");
			categorySearchContextDTO.eq("owner_subtype", "idea");
			categorySearchContextDTO.eq("owner_id", strProductId);
			categorySearchContextDTO.eq("section_id", section.getId());
			categorySearchContextDTO.sort("sequence, asc");
			
			Map<String, IEntityDTO> categoryMap = new LinkedHashMap();
			Map<String, PSSysReqModuleDTO> categoryPSSysReqModuleMap = new LinkedHashMap();
			
			List<IEntityDTO> categoryList = categoryDataEntityRuntime.selectDataSet("NO_PARENT", categorySearchContextDTO);
			if(!ObjectUtils.isEmpty(categoryList)) {
				for(IEntityDTO item : categoryList ) {
					//逐个演进
					String strCategoryName = item.getString("NAME", null);
					if(ObjectUtils.isEmpty(strCategoryName)) {
						continue;
					}
					
					String strCategoryId = item.getString("ID", null);
					categoryMap.put(strCategoryId, item);
					
					//判断是否有模块
					PSSysReqModuleDTO uiModulePSSysReqModule = uiModulePSSysReqModuleMap.get(strCategoryName);
					if(uiModulePSSysReqModule == null) {
						uiModulePSSysReqModule = new PSSysReqModuleDTO();
						uiModulePSSysReqModule.setPPSSysReqModuleId(screenshotPSSysReqModule.getPSSysReqModuleId());
						uiModulePSSysReqModule.setPSSysReqModuleName(strCategoryName);
						uiModulePSSysReqModule.setOrderValue(item.getInteger("SEQUENCE", 999999));
						uiModulePSSysReqModule.setModuleTag2("PDD_UIMODULE");
						this.iPSSysReqModuleService.create(uiModulePSSysReqModule);
						
						uiModulePSSysReqModule.put(strCategoryName, uiModulePSSysReqModule);						
					}
					else{
						//查出全部子模块
						ISearchContextDTO psSysReqModuleSearchContextDTO =  this.iPSSysReqModuleService.createSearchContextDTO();
						psSysReqModuleSearchContextDTO.all().count(false);
						psSysReqModuleSearchContextDTO.eq(PSSysReqModuleDTO.FIELD_PPSSYSREQMODULEID, uiModulePSSysReqModule.getPSSysReqModuleId());
						psSysReqModuleSearchContextDTO.eq(PSSysReqModuleDTO.FIELD_MODULETAG2, "PDD_UI")
						List<PSSysReqModuleDTO> psSysReqModuleDTOList = this.iPSSysReqModuleService.rawSelect(psSysReqModuleSearchContextDTO);
						if(!ObjectUtils.isEmpty(psSysReqModuleDTOList)) {
							for(PSSysReqModuleDTO psSysReqModuleDTO : psSysReqModuleDTOList) {
								if(!StringUtils.hasLength(psSysReqModuleDTO.getModuleSN())) {
									continue;
								}
								uiPSSysReqModuleMap.put(psSysReqModuleDTO.getModuleSN(), psSysReqModuleDTO);
							}
						}
					}
					
					categoryPSSysReqModuleMap.put(strCategoryId, uiModulePSSysReqModule);
				}
			}
			
			
			ISearchContextDTO ideaSearchContextDTO = ideaDataEntityRuntime.createSearchContext();
			ideaSearchContextDTO.all().count(false);
			ideaSearchContextDTO.eq("product_id", strProductId);
			ideaSearchContextDTO.eq("section_id", section.getId())
			List<IEntityDTO> ideaList = ideaDataEntityRuntime.selectDataSet("COMMON", ideaSearchContextDTO);
			if(!ObjectUtils.isEmpty(ideaList)) {
				for(IEntityDTO item : ideaList ) {
					//逐个演进
					String strIdentifier = item.getString("IDENTIFIER", null);
					if(ObjectUtils.isEmpty(strIdentifier)) {
						continue;
					}
					
					String strCategoryId = item.getString("CATEGORY_ID", null);
					if(ObjectUtils.isEmpty(strCategoryId)) {
						continue;
					}
					
					PSSysReqModuleDTO uiModulePSSysReqModule = categoryPSSysReqModuleMap.get(strCategoryId);
					if(uiModulePSSysReqModule == null) {
						continue;
					}
					
					
					//判断是否有模块
					PSSysReqModuleDTO uiPSSysReqModule = uiPSSysReqModuleMap.get(strIdentifier);
					if(uiPSSysReqModule == null) {
						uiPSSysReqModule = new PSSysReqModuleDTO();
						uiPSSysReqModule.setModuleSN(strIdentifier);
						uiPSSysReqModule.setPPSSysReqModuleId(uiModulePSSysReqModule.getPSSysReqModuleId());
						uiPSSysReqModule.setPSSysReqModuleName(item.getString("TITLE", null));
						uiPSSysReqModule.setOrderValue(item.getInteger("SEQUENCE", 999999));
						uiPSSysReqModule.setModuleTag2("PDD_UI");
						this.iPSSysReqModuleService.create(uiPSSysReqModule);
					}
					
					//判断AI构建状态
					int nAIBuildState = DataTypeUtils.asInteger(uiPSSysReqModule.getAIBuildMode(), AIBuildState.NOTSTARTED.value);
					if(nAIBuildState == 0) {
						//填充内容
						doBuildPSSysReqModuleContent(item, uiPSSysReqModule);
					}
				}
			}
		}
		
		//构建实体模块
		for(java.util.Map.Entry<String, PSSysReqModuleDTO> entry : uiModulePSSysReqModuleMap.entrySet()) {
			
			PSSysReqModuleDTO modulePSSysReqModule = modulePSSysReqModuleMap.get(entry.getKey());
			if(modulePSSysReqModule == null) {
				modulePSSysReqModule = new PSSysReqModuleDTO();
				modulePSSysReqModule.setPPSSysReqModuleId(modulesPSSysReqModule.getPSSysReqModuleId());
				modulePSSysReqModule.setPSSysReqModuleName(entry.getValue().getPSSysReqModuleName());
				modulePSSysReqModule.setOrderValue(entry.getValue().getOrderValue());
				modulePSSysReqModule.setModuleTag2("MDD_MODULE");
				this.iPSSysReqModuleService.create(modulePSSysReqModule);
				
				modulePSSysReqModuleMap.put(entry.getKey(), modulePSSysReqModule);
			}
		}
		
		
		ActionSessionManager.getAppContextIf().set(DEMODEL_PRODUCT, strLastProductId);
	}
	
	protected void doBuildPSSysReqModuleContent(IEntityDTO idea, PSSysReqModuleDTO psSysReqModule) throws Throwable{
		//获取讨论内容
		String strLastIdeaId = ActionSessionManager.getAppContextIf().get(DEMODEL_IDEA);
		String strIdeaId = idea.getId();
		ActionSessionManager.getAppContextIf().set(DEMODEL_IDEA, strIdeaId);
		
		ISearchContextDTO commentSearchContextDTO = commentDataEntityRuntime.createSearchContext();
		commentSearchContextDTO.all().count(false);
		commentSearchContextDTO.eq("owner_type", "idea");
		commentSearchContextDTO.eq("principal_id", strIdeaId);
		commentSearchContextDTO.sort("create_time ,asc")
		boolean bUpdate = false;
		if(StringUtils.hasLength(psSysReqModule.getContent())) {
			psSysReqModule.setContent(null);
			bUpdate = true;
		}
		
		if(StringUtils.hasLength(psSysReqModule.getReqModel())) {
			psSysReqModule.setReqModel(null);
			bUpdate = true;
		}
		
		List<IEntityDTO> commentList = commentDataEntityRuntime.selectDataSet("DEFAULT", commentSearchContextDTO);
		if(!ObjectUtils.isEmpty(commentList)) {
			for(IEntityDTO item : commentList ) {
				// 进行内容分析
				String text = item.getString("content", "");				
				// 创建 Matcher 对象，并匹配文本
				Matcher matcher = Regex.matcher(text);
	
				// 查找匹配的结果
				Map<String, String> replaceContentMap = new LinkedHashMap<>();
				Map<String, String> userIdMap = new LinkedHashMap<>();
				while (matcher.find()) {
					// 提取 JSON 内容
					String json = matcher.group(1);
					try {
						Map<String, Object> map = JsonUtils.asMap(json);
						Object userid = map.get("id");
						Object username = map.get("name");
						if(userid != null && username != null) {
							//替换新内容
							replaceContentMap.put(String.format("@%s", json), "\r\r");
							userIdMap.put(userid.toString(), username.toString());
						}
					} catch (Throwable ex) {
						log.error(String.format("转化值处理解析Json发生异常，%s", ex.getMessage()), ex);
					}
				}
	
				if(replaceContentMap.size() > 0) {
					//形成新内容
					for(java.util.Map.Entry<String, String> entry : replaceContentMap.entrySet()) {
						text = text.replace(entry.getKey(), entry.getValue());
					}
					
					text = SysHtml2MDTranslatorRuntime.toMD(text);
					text = text.replace("<br />", "\r").replace("<br/>", "\r");
					
					String strUserName = userIdMap.values().first();
					if(PLMUSER_AIREQ.equals(strUserName)) {
						if(!text.equals(psSysReqModule.getContent())) {
							String strLastContent = psSysReqModule.getContent();
							if(StringUtils.hasLength(strLastContent)) {
								strLastContent += "\r";
							}
							else {
								strLastContent = "";
							}
							strLastContent += text;
							psSysReqModule.setContent(strLastContent);
							bUpdate = true;
						}
					}
					else
						if(PLMUSER_AIJSON.equals(strUserName)) {
							if(!text.equals(psSysReqModule.getReqModel())) {
								psSysReqModule.setReqModel(text);
								bUpdate = true;
							}
						}
				}
			}
		}
		
		
		if(bUpdate) {
			this.iPSSysReqModuleService.update(psSysReqModule);
		}
		
		ActionSessionManager.getAppContextIf().set(DEMODEL_IDEA, strLastIdeaId);
	}
	
	
	protected void fillPageDTO(IEntityDTO pageDTO, int nType) {
		if(nType == 1) {
			pageDTO.set("type", 1);
			pageDTO.set("format_type", "HTML");
			pageDTO.set("is_published", 0);
			pageDTO.set("is_shared", 0);
			pageDTO.set("is_leaf", 1);
			pageDTO.set("is_archived", 0);
			pageDTO.set("is_deleted", 0);
			pageDTO.set("published", 0);
			pageDTO.set("is_lock", 0);
			pageDTO.set("is_shared_subset", 0);
			return;
		}
	}

	
	@Override
	protected void onUninstall() throws Throwable {
		this.getDEMethodPluginRuntimeRepo().shutdown();
		super.onUninstall();
	}
	
	
}
